#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int map[3][3];
char userChoice;
int playerSwitch=1;
struct Position pos;
int IsWin();
int NewGame();
void DrawMap();
int EmptyCount();
void interFace();
void WinInterface();
struct Position
{
	int x,y;	
};

int main()
{
	interFace();
	WinInterface();
}

void interFace()
{
	int i=0;
	printf("--------------------\n");
	printf("---1. play 2.eixt---\n");
	printf("--------------------\n");
	do
	{
		if(++i>1)	printf("Please input 1 or 2\n");
		userChoice=getch();
	}while(userChoice!=49 && userChoice!=50);
	if(userChoice==49)	NewGame();
	else	exit(0);
}
int NewGame()
{
	DrawMap();
	while(IsWin()==0)
	{
		do
		{
			printf("\nPlayer%d input--Row:",(playerSwitch%2==0)?2:1);
			userChoice=getch();
			pos.x=userChoice-'0';
		}while(pos.x>3); 
		do
		{
			printf("\nPlayer%d input--Col:",(playerSwitch%2==0)?2:1);
			userChoice=getch();
			pos.y=userChoice-'0';
		}while(pos.y>3);
		if(map[pos.x-1][pos.y-1]==0)
			map[pos.x-1][pos.y-1]=(playerSwitch%2==0)?2:1;
		else	continue;
		playerSwitch++;
		DrawMap();
		if(EmptyCount()==0)
			return 0;
	}
	return 1;
}
void DrawMap()
{
	system("cls");
	for(int r=0;r<3;r++)
	{
		printf("------------\n");
		for(int i=0;i<3;i++)
		{
			if(map[r][i]==0)	printf("   ");
			else if(map[r][i]==1)	printf(" o ");
			else if(map[r][i]==2)	printf(" x ");
			printf("|");
		}
		printf("\n");
	}
	printf("------------\n");
} 
int IsWin()
{
	int winCount;
	for(int r=0;r<3;r++)
	{
		winCount=0;
		int c=0;
		for(c=0;c<2;c++)	
			if(map[r][c]==map[r][c+1] && map[r][c]!=0)	winCount++;
		if(winCount==2)	return (map[r][c]==1)?1:2;
	}
	for(int c=0;c<3;c++)
	{
		winCount=0;
		int r=0;
		for(r=0;r<2;r++)
			if(map[r][c]==map[r+1][c] && map[r][c]!=0)	winCount++;
		if(winCount==2)	return (map[r][c]==1)?1:2;
	}
	if((map[0][0]==map[1][1] && map[1][1]==map[2][2]) && map[0][0]!=0)
		return (map[0][0]==1)?1:2;
	if((map[0][2]==map[1][1] && map[1][1]==map[2][0]) && map[0][2]!=0)
		return (map[0][2]==1)?1:2;
	return 0;
}
void WinInterface()
{
	if(NewGame()==1)
	{
		system("cls");
		printf("---------------\n");
		printf("   player%d win!!!   \n",IsWin());
		printf("----------------\n");
	}
	else
	{
		system("cls");
		printf("----------------\n");
		printf("      Equal     \n");
		printf("----------------\n");
	}
}
int EmptyCount()
{
	int emptyCount=0;
	for(int r=0;r<3;r++)
		for(int c=0;c<3;c++)	if(map[r][c]==0)	emptyCount++;
	return emptyCount;
}
